#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "linktable.h"

#define MAX_LEN 100

typedef struct tDataNode 
{
    tLinkTableNode *next;
    char   *cmd;
    char   *desc;
    int    (*handler)();
} DataNode;

DataNode* FindCmd(tLinkTable *head, const char *cmd);
void ShowAllCmd(tLinkTable *head);
int help();
int quit();

int InitMenuData(tLinkTable **ppLinktable)
{
    *ppLinktable = CreateLinkTable();
    DataNode *pNode = (DataNode *)malloc(sizeof(DataNode));
    pNode->cmd = "help";
    pNode->desc = "Show all menus";
    pNode->handler = help;
    AddLinkTableNode(*ppLinktable, (tLinkTableNode *)pNode);
    pNode = (DataNode *)malloc(sizeof(DataNode));
    pNode->cmd = "version";
    pNode->desc = "Menu Program V1.3";
    pNode->handler = NULL;
    AddLinkTableNode(*ppLinktable, (tLinkTableNode *)pNode);
    pNode = (DataNode *)malloc(sizeof(DataNode));
    pNode->cmd = "quit";
    pNode->desc = "Quit from Menu Program V1.3";
    pNode->handler = quit;
    AddLinkTableNode(*ppLinktable, (tLinkTableNode *)pNode);

    return 0;
}

tLinkTable *head = NULL;

int main(int argc, char *argv[])
{
    InitMenuData(&head);
    char cmd[MAX_LEN];
    while(1)
    {
        printf("Input a command: ");
        scanf("%s", cmd);
        
        DataNode *p = FindCmd(head, cmd); 
        if(NULL == p)
        {
            printf("Unknown command!\n");
            continue;
        }       

        if(strcmp(p->cmd, "help") != 0)
            printf("%-10s - %s\n", cmd, p->desc);
        if(NULL != p->handler)
        {
            if(-1 == p->handler())
                break;
        }             
    }
    DeleteLinkTable(head);

    return 0;
}

DataNode* FindCmd(tLinkTable *head, const char *cmd)
{
    DataNode *p = (DataNode *)GetLinkTableHead(head);
    while(NULL != p)
    {
        if(0 == strcmp(cmd, p->cmd))
            break;
        
        p = (DataNode *)GetNextLinkTableNode(head, (tLinkTableNode *)p);
    }
    
    return p;
}

void ShowAllCmd(tLinkTable *head)
{
    printf("Menu List:\n");
    
    DataNode *p = (DataNode *)GetLinkTableHead(head);
    while(NULL != p)
    {
        printf("%-10s - %s\n", p->cmd, p->desc);
        p = (DataNode *)GetNextLinkTableNode(head, (tLinkTableNode *)p);
    }
}

int help()
{
    ShowAllCmd(head);
    return 0;
}

int quit()
{
    return -1;
}
